package cn.gson.crm.controller.teaching;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gson.crm.model.dao.AnswerDao;
import cn.gson.crm.model.dao.ChutiDao;
import cn.gson.crm.model.dao.ClassDao;
import cn.gson.crm.model.dao.ExercisesDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.dao.WorkJinDuDao;
import cn.gson.crm.model.dao.WorkJournalDao;
import cn.gson.crm.model.dao.ZhangJieDao;
import cn.gson.crm.model.entity.Answer;
import cn.gson.crm.model.entity.Chuti;
import cn.gson.crm.model.entity.Classes;
import cn.gson.crm.model.entity.Exercises;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.User;
import cn.gson.crm.model.entity.WorkJinDu;
import cn.gson.crm.model.entity.WorkJournal;
import cn.gson.crm.model.entity.ZhangJie;
import cn.gson.crm.model.mapper.ClassesMapper;
import cn.gson.crm.model.mapper.WorkJinMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("/homework")
@Log4j
public class HomeworkController {

	@Autowired
	private WorkJinDuDao jdDao;

	@Autowired
	private ChutiDao ctDao;

	@Autowired
	private ClassDao claDao;

	@Autowired
	private ClassesMapper claMapper;

	@Autowired
	private WorkJinMapper jdMapper;

	@Autowired
	private ExercisesDao eiDao;

	@Autowired
	private ZhangJieDao zjDao;

	@Autowired
	private StudentDao stuDao;

	@Autowired
	private AnswerDao asDao;

	@Autowired
	private WorkJournalDao jlDao;

	@RequestMapping("/work/{id}")
	@Transactional
	public String addPayrecord(@PathVariable(name = "id", required = false) Long workid, HttpSession session,
			Model model) {
		// 获取登录用户session
		User user = (User) session.getAttribute("user");
		// log.info(user.getStudent());
		// 获取用户身份id
		Long cid = claMapper.returnclassid(user.getStudent().getId());

		// 通过用户身份id查询班级
		Classes cla = claDao.findOne(cid);
		// 存进model作用域
		model.addAttribute("cla", cla);
		Long sid = user.getStudent().getId();
		// 获取学生对象
		Student stu = stuDao.findOne(sid);
		// 出题信息
		Chuti ct = ctDao.findOne(workid);

		// 获取所有的试题id
		List<Long> eid = jdMapper.selectAllexce(workid);
		// 将所有试题存进集合
		List<Exercises> exers = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {

			Exercises exercises = eiDao.findOne(eid.get(i));
			exers.add(exercises);
		}
		List<Exercises> choises = new ArrayList<>();
		List<Exercises> opinions = new ArrayList<>();
		List<Exercises> programs = new ArrayList<>();
		List<Answer> choisesanswer = new ArrayList<>();
		List<Answer> opinionsanswer = new ArrayList<>();
		List<Answer> programsanswer = new ArrayList<>();
		Map<String, Object> choise = new HashMap<>();
		Map<String, Object> opinion = new HashMap<>();
		Map<String, Object> program = new HashMap<>();
		// 将试题分类opinion
		for (int i = 0; i < exers.size(); i++) {
			Answer as = new Answer();
			as.setStudent(stu);
			as.setWork(ct);
			if ("选择题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				choises.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						choisesanswer.add(answer);
					}
				}

			} else if ("判断题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);

				opinions.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						opinionsanswer.add(answer);
					}
				}
			} else if ("编程题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				programs.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						answer.setAnswer(answer.getAnswer().replaceAll("☽", "&"));
						programsanswer.add(answer);
					}
				}
			}
		}
		Exercises exer = new Exercises();
		for (int i = 0; i < eid.size(); i++) {
			exer = eiDao.findOne(eid.get(i));
			if (exer != null) {
				break;
			}
		}
		ZhangJie zj = zjDao.findOne(exer.getZhangJie().getId());
		choise.put("choises", choises);
		choise.put("choisesanswer", choisesanswer);

		opinion.put("opinions", opinions);
		opinion.put("opinionsanswer", opinionsanswer);
		program.put("programs", programs);
		program.put("programsanswer", programsanswer);

		model.addAttribute("ct", ct);
		model.addAttribute("zj", zj);
		model.addAttribute("choise", choise);
		model.addAttribute("opinion", opinion);
		model.addAttribute("program", program);
		return "homework/work";
	}

	@PostMapping("/saveanswer")
	@Transactional
	public String saveanswer(HttpServletRequest request, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Long sid = user.getStudent().getId();
		// 获取学生对象
		Student stu = stuDao.findOne(sid);
		String workid = request.getParameter("workid");
		Chuti ct = ctDao.findOne(Long.parseLong(workid));
		String[] cids = request.getParameterValues("answercid");
		String[] oids = request.getParameterValues("answeroid");
		String[] pids = request.getParameterValues("answerpid");
		List<String> answerc = new ArrayList<>();
		List<String> answero = new ArrayList<>();
		List<String> answerp = new ArrayList<>();
		String an = "";
		// 获取选择题答案
		if (cids != null) {
			for (int i = 0; i < cids.length; i++) {
				String[] canswer = request.getParameterValues("answer_" + cids[i]);
				if (canswer != null) {
					for (int j = 0; j < canswer.length; j++) {
						an = an + canswer[j];
					}
				}
				answerc.add(an);
				an = "";
			}
		}
		// 获取判断题答案
		if (oids != null) {
			for (int i = 0; i < oids.length; i++) {
				String canswer = request.getParameter("answer_" + oids[i]);
				answero.add(canswer);
			}
		}

		// 获取编程题答案
		if (pids != null) {
			for (int i = 0; i < pids.length; i++) {
				String canswer = request.getParameter("answer_" + pids[i]);
				answerp.add(canswer);
			}
		}
		if (cids != null) {
			for (int i = 0; i < cids.length; i++) {
				Long eid = Long.parseLong(cids[i]);
				Exercises quertion = eiDao.findOne(eid);
				Answer as = new Answer();
				as.setDelete(true);
				as.setQuertion(quertion);
				as.setStudent(stu);
				as.setWork(ct);
				as.setAnswer(answerc.get(i));
				Long awid = jdMapper.selectanswerid(as);
				as.setId(awid);
				asDao.save(as);
			}
		}
		if (oids != null) {
			for (int i = 0; i < oids.length; i++) {
				Long eid = Long.parseLong(oids[i]);
				Exercises quertion = eiDao.findOne(eid);
				Answer as = new Answer();
				as.setDelete(true);
				as.setQuertion(quertion);
				as.setStudent(stu);
				as.setWork(ct);
				as.setAnswer(answero.get(i));
				Long awid = jdMapper.selectanswerid(as);
				as.setId(awid);
				asDao.save(as);
			}
		}
		if (pids != null) {
			for (int i = 0; i < pids.length; i++) {
				Long eid = Long.parseLong(pids[i]);
				Exercises quertion = eiDao.findOne(eid);
				Answer as = new Answer();
				as.setDelete(true);
				as.setQuertion(quertion);
				as.setStudent(stu);
				as.setWork(ct);
				as.setAnswer(answerp.get(i));
				Long awid = jdMapper.selectanswerid(as);
				as.setId(awid);
				asDao.save(as);
			}
		}			
		WorkJinDu wjd = new WorkJinDu();
		  wjd.setStudent(stu); wjd.setWork(ct); Long jd = jdMapper.selectWorkjd(wjd);
		  WorkJinDu jds = jdDao.findOne(jd); jds.setState("进行中"); jdDao.save(jds);
		return "homework/work";
	}

	@RequestMapping("/subanswer")
	@Transactional
	@ResponseBody
	public Map<String, Object> subanswer(HttpServletRequest request,HttpSession session) {
		User user = (User) session.getAttribute("user");
		Long sid = user.getStudent().getId();
		// 获取学生对象
		Student stu = stuDao.findOne(sid);
		String workid = request.getParameter("workid");
		Chuti ct = ctDao.findOne(Long.parseLong(workid));
		String[] cids = request.getParameterValues("answercid");
		String[] oids = request.getParameterValues("answeroid");
		String[] pids = request.getParameterValues("answerpid");
		List<String> answerc = new ArrayList<>();
		List<String> answero = new ArrayList<>();
		List<String> answerp = new ArrayList<>();
		String an = "";
		// 获取选择题答案
		if (cids != null) {
			for (int i = 0; i < cids.length; i++) {
				String[] canswer = request.getParameterValues("answer_" + cids[i]);
				if (canswer != null) {
					for (int j = 0; j < canswer.length; j++) {
						an = an + canswer[j];
					}
				}
				answerc.add(an);
				an = "";
			}
		}
		// 获取判断题答案
		if (oids != null) {
			for (int i = 0; i < oids.length; i++) {
				String canswer = request.getParameter("answer_" + oids[i]);
				answero.add(canswer);
			}
		}

		// 获取编程题答案
		if (pids != null) {
			for (int i = 0; i < pids.length; i++) {
				String canswer = request.getParameter("answer_" + pids[i]);
				answerp.add(canswer);
			}
		}
		if (cids != null) {
			for (int i = 0; i < cids.length; i++) {
				Long eid = Long.parseLong(cids[i]);
				Exercises quertion = eiDao.findOne(eid);
				Answer as = new Answer();
				as.setDelete(true);
				as.setQuertion(quertion);
				as.setStudent(stu);
				as.setWork(ct);
				as.setAnswer(answerc.get(i));
				Long awid = jdMapper.selectanswerid(as);
				as.setId(awid);
				asDao.save(as);
			}
		}
		if (oids != null) {
			for (int i = 0; i < oids.length; i++) {
				Long eid = Long.parseLong(oids[i]);
				Exercises quertion = eiDao.findOne(eid);
				Answer as = new Answer();
				as.setDelete(true);
				as.setQuertion(quertion);
				as.setStudent(stu);
				as.setWork(ct);
				as.setAnswer(answero.get(i));
				Long awid = jdMapper.selectanswerid(as);
				as.setId(awid);
				asDao.save(as);
			}
		}
		if (pids != null) {
			for (int i = 0; i < pids.length; i++) {
				Long eid = Long.parseLong(pids[i]);
				Exercises quertion = eiDao.findOne(eid);
				Answer as = new Answer();
				as.setDelete(true);
				as.setQuertion(quertion);
				as.setStudent(stu);
				as.setWork(ct);
				as.setAnswer(answerp.get(i));
				Long awid = jdMapper.selectanswerid(as);
				as.setId(awid);
				asDao.save(as);
			}
		}
		Map<String, Object> obj = new HashMap<>();
		if (sid != null) {
				// 获取学生对象
				WorkJinDu wjd = new WorkJinDu();
				wjd.setStudent(stu);
				wjd.setWork(ct);
				
				Long jd = jdMapper.selectWorkjd(wjd);
				WorkJinDu jds = jdDao.findOne(jd);
				jds.setSavaWordtime(new Date());
				jds.setState("等待批改");
				jdDao.save(jds);
				
				WorkJournal workjl = new WorkJournal();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
				String today = df.format(new Date());// new Date()为获取当前系统时间
				workjl.setSavaWordtime(today);
				workjl.setStudent(stu);
				workjl.setWork(ct);
				jlDao.save(workjl);
		}
		return obj;
	}

	@RequestMapping("/seework/{id}")
	@Transactional
	public String seework(@PathVariable(name = "id", required = false) Long workid, HttpSession session, Model model) {
		// 获取登录用户session
		User user = (User) session.getAttribute("user");
		// 获取用户身份id
		Long cid = claMapper.returnclassid(user.getStudent().getId());
		// 通过用户身份id查询班级
		Classes cla = claDao.findOne(cid);
		// 存进model作用域
		model.addAttribute("cla", cla);
		Long sid = user.getStudent().getId();
		// 获取学生对象
		Student stu = stuDao.findOne(sid);
		// 出题信息
		Chuti ct = ctDao.findOne(workid);
		// 获取班级里所有学生id
		List<Long> stuid = claMapper.returnAllclastuid(cid);
		List<WorkJinDu> jdids = new ArrayList<>();
		for (int i = 0; i < stuid.size(); i++) {
			Student s = stuDao.findOne(stuid.get(i));
			log.info(s);
			WorkJinDu jd = new WorkJinDu();
			jd.setStudent(s);
			jd.setWork(ct);
			Long jdid = jdMapper.selectWorkjd(jd);
			if(jdid != null) {
				WorkJinDu jds = jdDao.findOne(jdid);
				jdids.add(jds);
			}
		}
		List<String> stuname = new ArrayList<>();
		List<Double> scores = new ArrayList<>();
		Double[] score = new Double[jdids.size()];
		String[] stunames = new String[jdids.size()];
		for (int i = 0; i < jdids.size(); i++) {
			stunames[i] = "'" + jdids.get(i).getStudent().getName() + "'";
			score[i] = jdids.get(i).getAllScore();
		}

		Double tag = null;
		String sname = null;
		for (int j = 0; j < score.length; j++) {
			if (score[j] == null) {
				score[j] = (double) 0;
			}
		}
		// 将成绩排序
		for (int i = 0; i < score.length - 1; i++) {
			for (int j = 0; j < score.length - i - 1; j++) {
				if (score[j] < score[j + 1]) {
					// 成绩排序
					tag = score[j];
					score[j] = score[j + 1];
					score[j + 1] = tag;
					// 姓名排序
					sname = stunames[j];
					stunames[j] = stunames[j + 1];
					stunames[j + 1] = sname;
				}
			}
		}
		for (int i = 0; i < stunames.length; i++) {
			stuname.add(stunames[i]);
			scores.add(score[i]);
		}
		// 获取所有的试题id
		List<Long> eid = jdMapper.selectAllexce(workid);
		// 将所有试题存进集合
		List<Exercises> exers = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises exercises = eiDao.findOne(eid.get(i));
			exers.add(exercises);
		}
		List<Exercises> choises = new ArrayList<>();
		List<Exercises> opinions = new ArrayList<>();
		List<Exercises> programs = new ArrayList<>();
		List<Answer> choisesanswer = new ArrayList<>();
		List<Answer> opinionsanswer = new ArrayList<>();
		List<Answer> programsanswer = new ArrayList<>();
		Map<String, Object> choise = new HashMap<>();
		Map<String, Object> opinion = new HashMap<>();
		Map<String, Object> program = new HashMap<>();
		// 将试题分类opinion
		for (int i = 0; i < exers.size(); i++) {
			Answer as = new Answer();
			as.setStudent(stu);
			as.setWork(ct);
			if ("选择题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				choises.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						choisesanswer.add(answer);
					}
				}

			} else if ("判断题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);

				opinions.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						opinionsanswer.add(answer);
					}
				}
			} else if ("编程题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				programs.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						programsanswer.add(answer);
					}
				}
			}
		}
		WorkJinDu wjd = new WorkJinDu();
		wjd.setStudent(stu);
		wjd.setWork(ct);
		Long jd = jdMapper.selectWorkjd(wjd);
		WorkJinDu jds = jdDao.findOne(jd);

		Exercises exer = eiDao.findOne(eid.get(0));
		ZhangJie zj = zjDao.findOne(exer.getZhangJie().getId());
		choise.put("choises", choises);
		choise.put("choisesanswer", choisesanswer);

		opinion.put("opinions", opinions);
		opinion.put("opinionsanswer", opinionsanswer);

		program.put("programs", programs);
		program.put("programsanswer", programsanswer);

		model.addAttribute("ct", ct);
		model.addAttribute("zj", zj);
		model.addAttribute("jds", jds);
		model.addAttribute("stuname", stuname);
		model.addAttribute("scores", scores);

		model.addAttribute("choise", choise);
		model.addAttribute("opinion", opinion);
		model.addAttribute("program", program);
		return "homework/seework";
	}

	@RequestMapping("mark_student_work/{wid}/{cid}")
	public String marking_work(@PathVariable(name = "wid", required = false) Long workid,
			@PathVariable(name = "cid", required = false) Long claid, Model model) {
		Chuti ct = ctDao.findOne(workid);
		Classes cla = claDao.findOne(claid);
		List<Long> stuids = claMapper.returnAllclastuid(claid);
		List<Long> jds = new ArrayList<>();
		List<Student> stus = new ArrayList<>();
		List<WorkJinDu> workjd = new ArrayList<>();
		//保存成绩
		//优
		List<Double> excellent = new ArrayList<>();
		//良
		List<Double> good = new ArrayList<>();
		//中
		List<Double> middle = new ArrayList<>();
		//差
		List<Double> difference = new ArrayList<>();
		//不及格
		List<Double> fail = new ArrayList<>();
		//未评定
		List<String> unassessed = new ArrayList<>();
		//保存这个班级所有学生姓名
		List<String> stuname = new ArrayList<>();
		//保存这个班每个学生的成绩
		List<Double> scores = new ArrayList<>();
		for (int i = 0; i < stuids.size(); i++) {
			Student stu = stuDao.findOne(stuids.get(i));
			WorkJinDu wjd = new WorkJinDu();
			wjd.setStudent(stu);
			wjd.setWork(ct);
			Long jdid = jdMapper.selectWorkjd(wjd);
			jds.add(jdid);
			stus.add(stu);
			stuname.add("'"+stu.getName()+"'");
		
		}
		for (int i = 0; i < jds.size(); i++) {
			if(jds.get(i) != null) {
				WorkJinDu jd = jdDao.findOne(jds.get(i));
				workjd.add(jd);
				if(jd.getAllScore() != null) {
					scores.add(jd.getAllScore());
					if(jd.getAllScore()<=100 && jd.getAllScore()>=90) {
						excellent.add(jd.getAllScore());
					}else if(jd.getAllScore()<=89 && jd.getAllScore()>=80) {
						good.add(jd.getAllScore());
					}else if(jd.getAllScore()<=79 && jd.getAllScore()>=70) {
						middle.add(jd.getAllScore());
					}else if(jd.getAllScore()<=69 && jd.getAllScore()>=60) {
						difference.add(jd.getAllScore());
					}else if (jd.getAllScore()<=59){
						fail.add(jd.getAllScore());
					}
				}else {
					scores.add(0D);
					unassessed.add(jd.getState());
				}
				
			}
		}
		List<Long> eid = jdMapper.selectAllexce(workid);
		List<ZhangJie> zj = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises e = eiDao.findOne(eid.get(i));
			ZhangJie zjs = zjDao.findOne(e.getZhangJie().getId());
			if (zjs != null) {
				zj.add(zjs);
			}
		}
		zj = removeDuplicate(zj);
		model.addAttribute("stus", stus);
		model.addAttribute("workjd", workjd);
		model.addAttribute("cla", cla);
		model.addAttribute("zj", zj);
		model.addAttribute("excellent", excellent);
		model.addAttribute("good", good);
		model.addAttribute("middle", middle);
		model.addAttribute("difference", difference);
		model.addAttribute("fail", fail);
		model.addAttribute("unassessed", unassessed);
		model.addAttribute("stuname", stuname);
		model.addAttribute("scores", scores);
		return "homework/mark_student_work";
	}

	// 去掉集合中相同数据
	private List<ZhangJie> removeDuplicate(List<ZhangJie> list) {
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = list.size() - 1; j > i; j--) {
				if (list.get(j).equals(list.get(i))) {
					list.remove(j);
				}
			}
		}
		return list;
	}

	@RequestMapping("seemarkwork/{wid}/{sid}")
	public String seemarkwork(@PathVariable(name = "wid", required = false) Long workid,
			@PathVariable(name = "sid", required = false) Long sid, Model model) {
		Chuti ct = ctDao.findOne(workid);
		Student stu = stuDao.findOne(sid);
		List<WorkJinDu> workjd = new ArrayList<>();
		// 获取所有的试题id
		List<Long> eid = jdMapper.selectAllexce(workid);
		// 将所有试题存进集合
		List<Exercises> exers = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises exercises = eiDao.findOne(eid.get(i));
			exers.add(exercises);
		}
		List<Exercises> choises = new ArrayList<>();
		List<Exercises> opinions = new ArrayList<>();
		List<Exercises> programs = new ArrayList<>();
		List<Answer> choisesanswer = new ArrayList<>();
		List<Answer> opinionsanswer = new ArrayList<>();
		List<Answer> programsanswer = new ArrayList<>();
		Map<String, Object> choise = new HashMap<>();
		Map<String, Object> opinion = new HashMap<>();
		Map<String, Object> program = new HashMap<>();
		// 将试题分类opinion
		for (int i = 0; i < exers.size(); i++) {
			Answer as = new Answer();
			as.setStudent(stu);
			as.setWork(ct);
			if ("选择题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				choises.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						choisesanswer.add(answer);
					}
				}

			} else if ("判断题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);

				opinions.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						opinionsanswer.add(answer);
					}
				}
			} else if ("编程题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				programs.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						programsanswer.add(answer);
					}
				}
			}
		}
		WorkJinDu wjd = new WorkJinDu();
		wjd.setStudent(stu);
		wjd.setWork(ct);
		Long jd = jdMapper.selectWorkjd(wjd);
		WorkJinDu jds = jdDao.findOne(jd);

		Exercises exer = eiDao.findOne(eid.get(0));
		ZhangJie zj = zjDao.findOne(exer.getZhangJie().getId());
		choise.put("choises", choises);
		choise.put("choisesanswer", choisesanswer);

		opinion.put("opinions", opinions);
		opinion.put("opinionsanswer", opinionsanswer);

		program.put("programs", programs);
		program.put("programsanswer", programsanswer);

		model.addAttribute("ct", ct);
		model.addAttribute("zj", zj);
		model.addAttribute("jds", jds);
		model.addAttribute("stu", stu);
		model.addAttribute("choise", choise);
		model.addAttribute("opinion", opinion);
		model.addAttribute("program", program);
		model.addAttribute("workjd", workjd);
		return "homework/seemarkwork";
	}

	@RequestMapping("seehomework/{wid}/{sid}")
	public String seehomework(@PathVariable(name = "wid", required = false) Long workid,
			@PathVariable(name = "sid", required = false) Long sid, Model model) {
		Chuti ct = ctDao.findOne(workid);
		Student stu = stuDao.findOne(sid);
		List<WorkJinDu> workjd = new ArrayList<>();
		// 获取所有的试题id
		List<Long> eid = jdMapper.selectAllexce(workid);
		// 将所有试题存进集合
		List<Exercises> exers = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises exercises = eiDao.findOne(eid.get(i));
			exers.add(exercises);
		}
		List<Exercises> choises = new ArrayList<>();
		List<Exercises> opinions = new ArrayList<>();
		List<Exercises> programs = new ArrayList<>();
		List<Answer> choisesanswer = new ArrayList<>();
		List<Answer> opinionsanswer = new ArrayList<>();
		List<Answer> programsanswer = new ArrayList<>();
		Map<String, Object> choise = new HashMap<>();
		Map<String, Object> opinion = new HashMap<>();
		Map<String, Object> program = new HashMap<>();
		// 将试题分类opinion
		for (int i = 0; i < exers.size(); i++) {
			Answer as = new Answer();
			as.setStudent(stu);
			as.setWork(ct);
			if ("选择题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				choises.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						choisesanswer.add(answer);
					}
				}

			} else if ("判断题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				opinions.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						opinionsanswer.add(answer);
					}
				}
			} else if ("编程题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				programs.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						programsanswer.add(answer);
					}
				}
			}
		}
		List<ZhangJie> zj = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises e = eiDao.findOne(eid.get(i));
			ZhangJie zjs = zjDao.findOne(e.getZhangJie().getId());
			if (zjs != null) {
				zj.add(zjs);
			}
		}
		zj = removeDuplicate(zj);
		choise.put("choises", choises);
		choise.put("choisesanswer", choisesanswer);

		opinion.put("opinions", opinions);
		opinion.put("opinionsanswer", opinionsanswer);

		program.put("programs", programs);
		program.put("programsanswer", programsanswer);
		model.addAttribute("ct", ct);
		model.addAttribute("zj", zj);
		model.addAttribute("choise", choise);
		model.addAttribute("opinion", opinion);
		model.addAttribute("program", program);
		model.addAttribute("workjd", workjd);
		model.addAttribute("stu", stu);
		return "homework/seehomework";
	}

	@RequestMapping("markingwork/{wid}/{sid}")
	@Transactional
	public String markingwork(@PathVariable(name = "wid", required = false) Long workid,
			@PathVariable(name = "sid", required = false) Long sid, Model model) {
		Chuti ct = ctDao.findOne(workid);
		Student stu = stuDao.findOne(sid);
		List<WorkJinDu> workjd = new ArrayList<>();
		// 获取所有的试题id
		List<Long> eid = jdMapper.selectAllexce(workid);
		// 将所有试题存进集合
		List<Exercises> exers = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises exercises = eiDao.findOne(eid.get(i));
			exers.add(exercises);
		}
		List<Exercises> choises = new ArrayList<>();
		List<Exercises> opinions = new ArrayList<>();
		List<Exercises> programs = new ArrayList<>();
		List<Answer> choisesanswer = new ArrayList<>();
		List<Answer> opinionsanswer = new ArrayList<>();
		List<Answer> programsanswer = new ArrayList<>();
		Map<String, Object> choise = new HashMap<>();
		Map<String, Object> opinion = new HashMap<>();
		Map<String, Object> program = new HashMap<>();
		// 将试题分类opinion
		for (int i = 0; i < exers.size(); i++) {
			Answer as = new Answer();
			as.setStudent(stu);
			as.setWork(ct);
			if ("选择题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				choises.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						choisesanswer.add(answer);
					}
				}

			} else if ("判断题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);

				opinions.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						opinionsanswer.add(answer);
					}
				}
			} else if ("编程题".equals(exers.get(i).getType())) {
				as.setQuertion(exers.get(i));
				Long ans = jdMapper.selectanswerid(as);
				programs.add(exers.get(i));
				if (ans != null) {
					Answer answer = asDao.findOne(ans);
					if (answer != null) {
						programsanswer.add(answer);
					}
				}
			}
		}
		List<ZhangJie> zj = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises e = eiDao.findOne(eid.get(i));
			ZhangJie zjs = zjDao.findOne(e.getZhangJie().getId());
			if (zjs != null) {
				zj.add(zjs);
			}
		}
		zj = removeDuplicate(zj);
		choise.put("choises", choises);
		choise.put("choisesanswer", choisesanswer);

		opinion.put("opinions", opinions);
		opinion.put("opinionsanswer", opinionsanswer);

		program.put("programs", programs);
		program.put("programsanswer", programsanswer);

		model.addAttribute("ct", ct);
		model.addAttribute("zj", zj);
		model.addAttribute("choise", choise);
		model.addAttribute("opinion", opinion);
		model.addAttribute("program", program);
		model.addAttribute("workjd", workjd);
		model.addAttribute("stu", stu);
		return "homework/markingwork";
	}

	/**
	 * 保存成绩
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("savesoure")
	@ResponseBody
	@Transactional
	public Map<String, Object> savesoure(HttpServletRequest request) {
		Map<String, Object> obj = new HashMap<>();
		Double score = Double.parseDouble(request.getParameter("txt_score"));
		Long wordid = Long.parseLong(request.getParameter("workid"));
		Long sid = Long.parseLong(request.getParameter("stuid"));
		String[] cid = request.getParameterValues("choiseids");
		String[] oid = request.getParameterValues("answeroid");
		String[] pid = request.getParameterValues("answerpid");
		String[] comment = request.getParameterValues("teacher_saying");
		String[] pscore = request.getParameterValues("program_score");
		String[] sscore = request.getParameterValues("select_score");
		String[] oscore = request.getParameterValues("judge_score");
		// 保存选择题分数
		if(cid != null) {
			for (int i = 0; i < cid.length; i++) {
				Long cids = Long.parseLong(cid[i]);
				Answer an = new Answer();
				an.setWork(ctDao.findOne(wordid));
				an.setStudent(stuDao.findOne(sid));
				an.setQuertion(eiDao.findOne(cids));
				Long aid = jdMapper.selectanswerid(an);
				Answer newan = asDao.findOne(aid);
				newan.setScore(Double.parseDouble(sscore[i]));
				asDao.save(newan);
			}
		}
		if(oid != null) {
			// 保存判断题分数
			for (int i = 0; i < oid.length; i++) {
				Long oids = Long.parseLong(oid[i]);
				Answer an = new Answer();
				an.setWork(ctDao.findOne(wordid));
				an.setStudent(stuDao.findOne(sid));
				an.setQuertion(eiDao.findOne(oids));
				Long aid = jdMapper.selectanswerid(an);
				Answer newan = asDao.findOne(aid);
				newan.setScore(Double.parseDouble(oscore[i]));
				asDao.save(newan);
			}
		}
		if(pid != null) {
			for (int i = 0; i < pid.length; i++) {
				Long pids = Long.parseLong(pid[i]);
				Answer an = new Answer();
				an.setWork(ctDao.findOne(wordid));
				an.setStudent(stuDao.findOne(sid));
				an.setQuertion(eiDao.findOne(pids));
				Long aid = jdMapper.selectanswerid(an);
				Answer newan = asDao.findOne(aid);
				newan.setScore(Double.parseDouble(pscore[i]));
				if (comment[i] != null) {
					newan.setComment(comment[i]);
				}
				asDao.save(newan);
			}
		}
		
		obj.put("success", false);
		Chuti ct = ctDao.findOne(wordid);
		Student stu = stuDao.findOne(sid);
		WorkJinDu as = new WorkJinDu();
		as.setStudent(stu);
		as.setWork(ct);
		Long jdid = jdMapper.selectWorkjd(as);
		if (jdid != null) {
			WorkJinDu jd = jdDao.findOne(jdid);
			if (jd != null) {
				jd.setAllScore(score);
				jd.setState("已批阅");
				jdDao.save(jd);
				obj.put("success", true);
			}
		} else {
			obj.put("message", "阅卷失败");
		}
		return obj;
	}

	/**
	 * 查看新作业
	 * 
	 * @param workid
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/seenewwork/{wid}")
	@Transactional
	public String seenewwork(@PathVariable(name = "wid", required = false) Long workid, HttpSession session,
			Model model) {
		// 出题信息
		Chuti ct = ctDao.findOne(workid);
		// 获取所有的试题id
		List<Long> eid = jdMapper.selectAllexce(workid);
		// 将所有试题存进集合
		List<Exercises> exers = new ArrayList<>();
		for (int i = 0; i < eid.size(); i++) {
			Exercises exercises = eiDao.findOne(eid.get(i));
			exers.add(exercises);
		}
		List<Exercises> choises = new ArrayList<>();
		List<Exercises> opinions = new ArrayList<>();
		List<Exercises> programs = new ArrayList<>();
		// 将试题分类opinion
		for (int i = 0; i < exers.size(); i++) {
			if ("选择题".equals(exers.get(i).getType())) {
				choises.add(exers.get(i));

			} else if ("判断题".equals(exers.get(i).getType())) {
				opinions.add(exers.get(i));
			} else if ("编程题".equals(exers.get(i).getType())) {
				programs.add(exers.get(i));
			}
		}
		Exercises exer = eiDao.findOne(eid.get(0));
		ZhangJie zj = zjDao.findOne(exer.getZhangJie().getId());
		model.addAttribute("ct", ct);
		model.addAttribute("zj", zj);
		model.addAttribute("choice", choises);
		model.addAttribute("option", opinions);
		model.addAttribute("program", programs);
		return "homework/seenewwork";
	}

	/**
	 * 延长作业时间
	 * 
	 * @param wid
	 * @param extend
	 * @return
	 */
	@RequestMapping("updateentime/{wid}/{extend}")
	@Transactional
	@ResponseBody
	public Map<String, Object> updateentime(@PathVariable(name = "wid", required = false) Long wid,
			@PathVariable(name = "extend", required = false) int extend) {
		Map<String, Object> obj = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		obj.put("success", false);
		Chuti ct = ctDao.findOne(wid);
		Date dt = null;
		try {
			dt = sdf.parse(ct.getEndTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.DAY_OF_YEAR, extend);// 日期加10天
		Date dt1 = rightNow.getTime();
		String reStr = sdf.format(dt1);
		ct.setEndTime(reStr);
		ctDao.save(ct);
		obj.put("success", true);
		obj.put("message", "修改失败");
		return obj;
	}

	/**
	 * 修改分数
	 * 
	 * @param wid
	 * @param sid
	 * @return
	 */
	@RequestMapping("againmark/{wid}/{sid}")
	@Transactional
	@ResponseBody
	public Map<String, Object> againmark(@PathVariable(name = "wid", required = false) Long wid,
			@PathVariable(name = "sid", required = false) Long sid) {
		Map<String, Object> obj = new HashMap<>();
		obj.put("success", false);
		WorkJinDu wjd = new WorkJinDu();
		wjd.setWork(ctDao.findOne(wid));
		wjd.setStudent(stuDao.findOne(sid));
		Long jdid = jdMapper.selectWorkjd(wjd);

		WorkJinDu jd = jdDao.findOne(jdid);
		jd.setState("等待批改");
		jd.setAllScore(null);
		jdDao.save(jd);
		obj.put("success", true);
		return obj;
	}

	/**
	 * 重做
	 * 
	 * @param jdid
	 * @return
	 */
	@RequestMapping("redowork/{jdid}")
	@Transactional
	@ResponseBody
	public Map<String, Object> redowork(@PathVariable(name = "jdid", required = false) Long jdid) {
		Map<String, Object> obj = new HashMap<>();
		obj.put("success", false);
		WorkJinDu jd = jdDao.findOne(jdid);
		jd.setState("进行中");
		jd.setAllScore(null);
		jdDao.save(jd);
		obj.put("success", true);
		return obj;
	}
}
